<template>
  <!-- 外层容器：flex 横向排列，全屏高度，间距4，内边距4 -->
  <div class="flex h-screen gap-4 p-4 bg-gray-100">
    
    <!-- 左侧面板：固定宽度80（320px），纵向flex，白色背景，圆角，阴影 -->
    <div class="w-80 min-w-70 max-w-md flex flex-col bg-white rounded-lg shadow-md">
      <!-- 顶部按钮区：有内边距，底部边框，灰色背景，固定高度 -->
      <div class="p-3 px-4 border-b border-gray-200 bg-gray-50 flex-shrink-0 min-h-[48px]">
        <ActionButtonGroup         
          :show-add="hasPermission('Add')"  
          :show-edit="hasPermission('Edit')"  
          :show-delete="hasPermission('Delete')" 
          :disabled-add="false"
          :disabled-edit="disabledEdit"
          :disabled-delete="disabledDelete"  
          @add="handleAdd"
          @edit="handleEdit"
          @delete="handleDelete"         
        />
      </div>
      
      <!-- 树形控件区：占满剩余高度，有内边距，可滚动 -->
      <div class="flex-1 p-4 overflow-hidden flex flex-col">
        <TreeFilter
          ref="treeFilterRef"
          :data="departmentData"
          :filter-fields="['label', 'name', 'code']"
          placeholder="搜索数字字典"
          @node-click="handleNodeClick"
          class="flex-1 overflow-auto"
        />
      </div>
    </div>

    <!-- 右侧面板：占据剩余空间，纵向flex，白色背景，圆角，阴影 -->
    <div class="flex-1 flex flex-col bg-white rounded-lg shadow-md">
      <!-- 顶部按钮区 -->
      <div  v-if="showLineForm"  class="p-3 px-4 border-b border-gray-200 bg-gray-50 flex-shrink-0 min-h-[48px]">
        <ActionButtonGroup            
          :show-add="hasPermission('lineAdd')"  
          :show-edit="hasPermission('lineEdit')"  
          :show-delete="hasPermission('lineDelete')" 
          :disabled-add="disabledLineAdd"
          :disabled-edit="disabledLineEdit"
          :disabled-delete="disabledLineDelete"  
          @add="handleLineAdd"
          @edit="handleLineEdit"
          @delete="handleLineDelete"        
        />
      </div>
      
      <!-- 表格控件区 -->
      <div v-if="showLineForm" class="flex-1 p-4 overflow-hidden flex flex-col">
        <!-- 在这里放置你的 CustomTable 组件 -->
         <CustomTable
      :tableColumns="columns"
      :tableData="data"
      :pageSize="pageSize"
      :pageSizes="pageSizes"
      :showSelection="true"
      @update:currentPage="currentPage = $event"
      @update:pageSize="pageSize = $event"
      @selection-change="handleSelectionChange"
     
    />
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="formTitle"
      width="80%"
      top="5vh"      
      :before-close="handleClose"
      fullscreen
    >
      <FormComponent
        ref="formComponentRef"
        :fields="fields"
        v-model:data="formData"
        @update:data="handleFormDataUpdate"
      ></FormComponent>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">{{ $t('btn.cancel') }}</el-button>
          <el-button type="primary" @click="handleSave">{{ $t('btn.save') }}</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref,onMounted,computed,reactive,nextTick } from 'vue'
import { usePermission } from "@/utils/permissionUtils";
import TreeFilter from '@/components/ActionTreeFilterCont.vue'
import ActionButtonGroup from "@/components/ActionBtnHdrCont.vue";
import CustomTable from '@/components/ActionTableCont.vue';
import FormComponent from "@/components/ActionFormCont.vue";
import defaultConfig from '@config'; // 相对路径
import { getFields } from '@/api/admin';
import { createQueryParams } from '@/utils';

import { msgError,msg18n } from '@/utils/msg';
import { useI18n } from 'vue-i18n'; // 
import { buildValidator } from '@/utils/buildValidator';
import { validatorPool } from '@/utils/validatorPool'
import { remove,  query, doFormSave } from '@/utils/apiHelper';

const hasPermission = usePermission();
const { t } = useI18n(); // 解构出 t 函数

const currentPage = ref(defaultConfig.tableCurrentPage);// 默认当前页为1
const pageSize = ref(defaultConfig.tablePageSize);// 默认每页显示10条数据
const pageSizes = ref(defaultConfig.tablePageSizes);// 默认分页大小为[10,20,50,100]


 // 1. 声明响应式数据
const columns = ref<any[]>([])   // 字段配置
const columns_header = ref<any[]>([])   // 字段配置
const columns_line = ref<any[]>([])   // 字段配置
const columns_item = ref<any[]>([])   // 字段配置
const data    = ref<any[]>([])   // 表格数据
const formData = ref({});
const dialogVisible = ref(false);
const formComponentRef = ref(null);
const fields = ref<any[]>([])
const fields_header = ref<any[]>([])
const fields_line = ref<any[]>([])
const fields_item = ref<any[]>([])
const disabledEdit= ref(true);
const disabledDelete= ref(true);
const disabledLineAdd= ref(true);
const disabledLineEdit= ref(true);
const disabledLineDelete= ref(true);
const showLineForm= ref(false);


const selectedData = ref([]);
const selectedTreeData = ref([]);

const api_module_getDict = 'dictTree';
const api_module = 'dictHeader';
const api_module_line = 'dictValue';
const api_module_item = 'dictTable';
const api_fields='dict_header'
const api_fields_line='dict_value'
const api_fields_item='dict_table'

let msg='';


const treeFilterRef = ref()
const departmentData = ref<any[]>([]) 

const btnMode = ref<'add' | 'edit'>('add')
const initParams = ref<Record<string, unknown>>({});
 

const formTitle = computed(() => {
  console.log('btnMode.value',btnMode.value);
  return btnMode.value === 'add' ? '添加菜单' : '编辑菜单'

});

async function fetchDatas(model: string,
                          params: Record<string, any> = {},
                          id?: string | number) 
  {
  try {
  
     // const QueryParams=createQueryParams({data: params}) 
     const QueryParams = id != null ? undefined : createQueryParams({ data: params });
     const action = id != null ? 'selectById' : 'select';
    const res= await query(model,action,QueryParams,id)
    return res.details ?? []   // 按后端实际字段返回
  } catch {
    msg=t('message.apiException');
    msgError(msg)
    return Promise.reject(new Error(msg))
  }
}
function getQueryParams(params: Record<string, any> = {}) {
  return {
    deletion_mark: 0,   // 固定默认值
    ...params,          // 外部传入的任意字段覆盖/追加
  };
}

// 2. 真正加载函数
async function loadData() {
  try {
   
    const QueryParams = getQueryParams({});
  
    // 并发请求
    const [fieldRes,dictRes] = await Promise.all([
      getFields(api_fields+','+api_fields_line+','+api_fields_item).catch(() => Promise.reject(new Error('字段接口异常'))),
      query(api_module_getDict,'selectQuery',{})       
    ])
 
    // 赋值（可选链兜底）    
    console.log("dictRes.data",dictRes)
    departmentData.value  =dictRes ?? []
    columns_header.value      = fieldRes.data?.[api_fields] ?? []
    columns_line.value      = fieldRes.data?.[api_fields_line] ?? [] 
    columns_item.value      = fieldRes.data?.[api_fields_item] ?? [] 
     // 生成表单字段
    fields_header.value = (fieldRes.data?.[api_fields] || []).map(f => ({
      ...f,
      rules: f.Validation
        ? [{ validator: buildValidator({ ...f.Validation, fieldName: f.label }), trigger: f.Validation.trigger || 'blur' }]
        : undefined
    })) ?? []

    fields_line.value =(fieldRes.data?.[api_fields_line] || []).map(f => ({
      ...f,
      rules: f.Validation
        ? [{ validator: buildValidator({ ...f.Validation, fieldName: f.label }), trigger: f.Validation.trigger || 'blur' }]
        : undefined
    })) ?? []

        fields_item.value =(fieldRes.data?.[api_fields_item] || []).map(f => ({
      ...f,
      rules: f.Validation
        ? [{ validator: buildValidator({ ...f.Validation, fieldName: f.label }), trigger: f.Validation.trigger || 'blur' }]
        : undefined
    })) ?? []

  } catch (e: any) {
    msg=t('message.apiException');
    msgError(`${msg}：${e.message}`)
  }
}

async function reloadData(model:string,params: Record<string, any> = {}) {
  try {
    if (model===api_module)
    {
      const dictRes = await query(api_module_getDict,'selectQuery',{}) 
      departmentData.value  =dictRes ?? []
    }
    else{
     
    const QueryParams = getQueryParams(params);
       
     const tableRes = await fetchDatas(model,QueryParams); 
     data.value    = tableRes//.details   ?? []
    }


  } catch (e: any) {
    msg=t('message.apiException');
    msgError(`${msg}：${e.message}`)
  }
}

async function reloadDataById(model:string,id: string | number) {
  try {
    console.log('reload.params id:', id);
    const dataRes = await fetchDatas(model,undefined, id); // model 固定为 user，可按需改为参数
    return dataRes;                                 // 单条对象
  } catch (e: any) {
    msg = t('message.apiException');
    msgError(`${msg}：${e.message}`);
    return null;                                     // 详情场景建议返回 null
  }
}


// 页面首次加载时候加载数据

onMounted(() => {
   loadData(); // 调用 loadData

});
const formInit = () => reactive({  
  enabled: true,
  sort: 10
})
const handleAdd = () => {
    console.log('点击添加')
    console.log('fields_header.value;',fields_header.value);
    // formComponentRef.value?.resetFields() 
    fields.value=fields_header.value;
    formData.value=formInit.value;
    
    dialogVisible.value = true;

  }
async function handleEdit()  {
  console.log('点击编辑')
  console.log('点击编辑',selectedTreeData.value.id)
  fields.value=fields_header.value;
  try{
      const retVar=await reloadDataById(api_module,selectedTreeData.value.id);
      formData.value=retVar[0];
      dialogVisible.value = true;
    }
    catch(e){
      console.log(e);
    }
}

async function handleDelete() {
    try{  
       console.log('selectedTreeData.value',selectedTreeData.value)
        await remove(api_module, 'mark', [selectedTreeData.value]);
        
        await reloadData(api_module,{});
        }
        catch(e:any){
          
        }
}

const handleSearch = () => {
    console.log('点击添加')
}

// 点击节点

export interface DictMeta {
  fields: any[];
  columns: any[];
  module: string;
}

/* ===== 配置表 ===== */
const dictMetaMap: Record<string, () => DictMeta> = {
  T: () => ({
    fields:  fields_item.value,
    columns: columns_item.value,
    module:  api_module_line,
  }),
  C: () => ({
    fields:  fields_line.value,
    columns: columns_line.value,
    module:  api_module_item,
  }),
}



function handleNodeClick(data: any) {
  console.log('点击节点:', data);

  selectedTreeData.value = { id: data.id, dict_type: data.dict_type };

  /* ---- 根节点不处理 ---- */
  if (data.parent_id === '0') {
    showLineForm.value = false;
    return;
  }
 selectedTreeData.value={id:data.id,dict_type:data.dict_type};
  let module = ''
  disabledLineAdd.value=false;
  console.log('data.dict_type',data.dict_type)
  if (data.dict_type==='T')
  {
    // fields.value=fields_item.value;
    columns.value=columns_item.value;
    module=api_module_item ;
  }
  else if(data.dict_type==='C')
  {
    // fields.value=fields_line.value;
    columns.value=columns_line.value;
    module=api_module_line ;
  }
    initParams.value={dict_id:data.id} ;
  console.log('columns.value',columns.value);

  reloadData(module,initParams.value)
  showLineForm.value =  data.parent_id !== '0';
  disabledEdit.value =false;
  disabledDelete.value = false;
 

}
/** T 只有 id */
const initT = () => reactive({ dict_id: selectedTreeData.value.id })

/** C 需要 id + enabled + sort */
const initC = () => reactive({
  dict_id: selectedTreeData.value.id,
  enabled: true,
  sort: 10
})


const handleLineAdd = () => {
  console.log('点击明细添加', selectedTreeData.value)
   
   // 1. 根据类型给不同的默认值（保证响应式）
  formData.value = selectedTreeData.value.dict_type === 'T'
    ? initT()
    : selectedTreeData.value.dict_type === 'C'
    ? initC()
    : reactive({})   // 兜底

  // 2. 字段数组
  fields.value = selectedTreeData.value.dict_type === 'T'
    ? fields_item.value
    : selectedTreeData.value.dict_type === 'C'
    ? fields_line.value
    : []
  
  dialogVisible.value = true
  //formComponentRef.value?.resetFields()
}
const handleLineEdit = () => {
       // 1. 根据类型给不同的默认值（保证响应式）
 
    formData.value={ ...selectedData.value[0] };
    // 2. 字段数组
   fields.value = selectedTreeData.value.dict_type === 'T'
    ? fields_item.value
    : selectedTreeData.value.dict_type === 'C'
    ? fields_line.value
    : []

    dialogVisible.value = true
}

const handleLineDelete = async () => {
  try {
    const module = selectedTreeData.value.dict_type === 'T'
      ? api_module_item
      : selectedTreeData.value.dict_type === 'C'
      ? api_module_line
      : '';

    if (!module) return;
    console.log('selectedData.value',selectedData.value);

    await remove(module, 'mark', selectedData.value);
    initParams.value = { dict_id: selectedTreeData.value.id };
    await reloadData(module, initParams.value);
  } catch (e: any) {
    /* 空 catch 建议至少打印 */
    console.error(e);
  }
};
const handleSelectionChange = (selection) => {
  selectedData.value = selection;
  disabledLineEdit.value = selection.length !== 1;
  disabledLineDelete.value = selection.length === 0;

};

const handleCancel = async () => {
  try {
    await nextTick() // 把可能存在的异步操作也包进来
    //formComponentRef.value?.resetFields()
    dialogVisible.value = false
  } catch (e) {
    console.error('原始错误：', e)
  }
}


const handleSave = async () => {
  // 1. 先决定 module
  let module = ''
  if (fields.value === fields_header.value) {
    module = api_module          // 'dictHeader'
    initParams.value={dict_id:data.id} ;
  } else if (fields.value === fields_line.value) {
    module = api_module_line     // 'dictValue'
    initParams.value={dict_id:formData.value['dict_id']} ;
  } else if (fields.value === fields_item.value) {
    module = api_module_item     // 'dictTable'
    initParams.value={dict_id:formData.value['dict_id']}
  } else {
    msgError('未知表单类型')
    return
  }
 
 
  // 2. 统一调保存
  const res = await doFormSave({
    module,
    formData: formData.value,
    formRef : formComponentRef.value?.$refs.formRef
  })
   
  dialogVisible.value = false;

  /* 3. 后续动作：关闭弹窗、刷新列表等 */
  reloadData(module,initParams.value)
};

const handleClose = (done: () => void) => {
  dialogVisible.value = false;
  done();
};

const handleFormDataUpdate = (newData: any) => {
  formData.value = { ...newData };
};


// 获取选中数据
const getChecked = () => {
  const nodes = treeFilterRef.value?.getCheckedNodes()
  
  console.log('选中节点:', nodes)
}
</script>